<template>
  <view class="container">
    <!-- 背景效果 - 气泡动画 -->
    <view class="background-overlay"></view>

    <!-- 主内容区 -->
    <view class="content-wrapper">
      <!-- 顶部导航区 -->
      <view class="top-navigation">
        <!-- 返回按钮 -->
        <view class="floating-close-btn" @click="goBack">
          <text class="close-icon">✕</text>
        </view>
        <!-- 页面标题 -->
        <view class="page-title">
          <text class="title-text">奶量趋势分析</text>
        </view>
        <view class="placeholder"></view>
      </view>

      <!-- 时间范围选择区 -->
      <view class="time-range-selector">
        <view 
          v-for="(range, index) in timeRanges" 
          :key="index" 
          class="time-range-option"
          :class="{ active: selectedTimeRange === range.value }"
          @click="changeTimeRange(range.value)">
          <text>{{ range.label }}</text>
        </view>
      </view>

      <!-- 页面内容区域 -->
      <view class="content-section">
        <!-- 数据统计汇总 -->
        <view class="chart-summary">
          <view class="summary-item">
            <text class="summary-label">{{ summaryLabel }}</text>
            <text class="summary-value">{{ weeklyTotalAmount }}ml</text>
          </view>
          <view class="summary-item">
            <text class="summary-label">平均每天</text>
            <text class="summary-value">{{ averageDailyAmount }}ml</text>
          </view>
          <view class="summary-item">
            <text class="summary-label">总喂养次数</text>
            <text class="summary-value">{{ weeklyTotalCount }}次</text>
          </view>
        </view>

        <!-- 奶量趋势图表 -->
        <view class="chart-section">
          <view class="chart-section-title">
            <view class="title-icon" style="background: #ff69b4;"></view>
            <view class="title-text">每日奶量趋势 (ml)</view>
          </view>
          <view class="chart-wrapper">
            <qiun-data-charts type="line" :chartData="milkAmountChartData" :opts="milkAmountChartOpts" :loadingType="2" :animation="true" :ontouch="false" :tooltipShow="true" style="width: 100%; height: 220px;" @getIndex="onMilkAmountChartClick" />
          </view>
        </view>

        <!-- 喂养次数图表 -->
        <view class="chart-section">
          <view class="chart-section-title">
            <view class="title-icon" style="background: #ff69b4;"></view>
            <text class="title-text">每日喂养次数</text>
          </view>
          <view class="chart-wrapper">
            <qiun-data-charts type="column" :chartData="feedCountChartData" :opts="feedCountChartOpts" :loadingType="2" :animation="true" :ontouch="false" :tooltipShow="true" style="width: 100%; height: 200px;" @getIndex="onFeedCountChartClick" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MilkTrendChart',
  data() {
    return {
      chartLoading: true,
      
      // 时间范围选择
      selectedTimeRange: '7days',
      timeRanges: [
        { label: '7天', value: '7days' },
        { label: '30天', value: '30days' },
        { label: '本月', value: 'thisMonth' }
      ],
      
      // 奶量趋势图表数据
      milkAmountChartData: {
        categories: [],
        series: []
      },
      milkAmountChartOpts: {
        color: ['#ff69b4'],
        padding: [15, 15, 10, 15],
        enableScroll: false,
        fontSize: 11,
        fontColor: '#ffffff',
        background: 'rgba(0,0,0,0)',
        legend: {
          show: false
        },
        xAxis: {
          disableGrid: true,
          fontSize: 11,
          fontColor: '#ffffff',
          axisLineColor: '#ffffff'
        },
        yAxis: {
          gridType: 'dash',
          gridColor: '#ffffff',
          dashLength: 2,
          fontSize: 11,
          fontColor: '#ffffff',
          data: [
            {
              min: 0,
              position: 'left',
              axisLine: true,
              axisLineColor: '#ffffff'
            }
          ]
        },
        extra: {
          line: {
            type: 'curve',
            width: 2.5,
            activeType: 'hollow',
            animation: true
          },
          tooltip: {
            showCategory: true,
            bgColor: '#000000',
            bgOpacity: 0.7,
            fontSize: 12,
            fontColor: '#FFFFFF'
          }
        }
      },

      // 喂养次数图表数据
      feedCountChartData: {
        categories: [],
        series: []
      },
      feedCountChartOpts: {
        color: ['#ff69b4'],
        padding: [15, 15, 10, 15],
        enableScroll: false,
        fontSize: 11,
        fontColor: '#ffffff',
        background: 'rgba(0,0,0,0)',
        legend: {
          show: false
        },
        xAxis: {
          disableGrid: true,
          fontSize: 11,
          fontColor: '#ffffff',
          axisLineColor: '#ffffff'
        },
        yAxis: {
          gridType: 'dash',
          gridColor: '#ffffff',
          dashLength: 2,
          fontSize: 11,
          fontColor: '#ffffff',
          data: [
            {
              min: 0,
              max: 10,
              position: 'left',
              axisLine: true,
              axisLineColor: '#ffffff'
            }
          ]
        },
        extra: {
          column: {
            width: 25,
            seriesGap: 1,
            categoryGap: 3
          },
          tooltip: {
            showCategory: true,
            bgColor: '#000000',
            bgOpacity: 0.7,
            fontSize: 12,
            fontColor: '#FFFFFF'
          }
        }
      },
      
    }
  },
  computed: {
    summaryLabel() {
      switch(this.selectedTimeRange) {
        case '7days':
          return '7天总奶量';
        case '30days':
          return '30天总奶量';
        case 'thisMonth':
          return '本月总奶量';
        default:
          return '总奶量';
      }
    },
    
    weeklyTotalAmount() {
      return this.milkAmountChartData.series.length > 0 &&
        this.milkAmountChartData.series[0].data
        ? this.milkAmountChartData.series[0].data.reduce(
            (sum, amount) => sum + amount,
            0
          )
        : 0
    },

    averageDailyAmount() {
      return this.milkAmountChartData.categories &&
        this.milkAmountChartData.categories.length > 0
        ? Math.round(
            this.weeklyTotalAmount / this.milkAmountChartData.categories.length
          )
        : 0
    },

    weeklyTotalCount() {
      return this.feedCountChartData.series.length > 0 &&
        this.feedCountChartData.series[0].data
        ? this.feedCountChartData.series[0].data.reduce(
            (sum, count) => sum + count,
            0
          )
        : 0
    }
  },
  onLoad() {
    this.prepareChartData()
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 切换时间范围
    changeTimeRange(range) {
      if (this.selectedTimeRange !== range) {
        this.selectedTimeRange = range
        this.prepareChartData()
      }
    },
    
    // 格式化日期用于输入
    formatDateForInput(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 格式化图表显示的日期
    formatDateForChart(date) {
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${month}/${day}`
    },
    
    // 格式化图表显示的日期(简化版,仅显示日期)
    formatDateForChartSimple(date) {
      return String(date.getDate()).padStart(2, '0')
    },

    // 获取指定日期的记录
    async fetchRecordsForDate(dateStr) {
      try {
        console.log(`🔍 调用云函数查询日期: ${dateStr}`)
        const result = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'get',
            data: { date: dateStr }
          }
        })

        if (result.result.success) {
          console.log(`✅ ${dateStr} 成功获取 ${result.result.data.length} 条记录`)
          return result.result.data
        }

        console.log(`⚠️ ${dateStr} 无数据或请求失败:`, result.result)
        return []
      } catch (error) {
        console.error(`❌ 获取日期记录失败 (${dateStr}):`, error)
        return []
      }
    },
    
    // 获取日期范围内的记录
    async fetchRecordsForDateRange(startDateStr, endDateStr) {
      try {
        console.log(`🔍 调用云函数查询日期范围: ${startDateStr} 至 ${endDateStr}`)
        const result = await uniCloud.callFunction({
          name: 'milk-record-service',
          data: {
            action: 'getDateRange',
            data: { 
              startDate: startDateStr,
              endDate: endDateStr
            }
          }
        })

        if (result.result.success) {
          console.log(`✅ 日期范围查询成功获取 ${result.result.data.length} 条记录`)
          return result.result.data
        }

        console.log(`⚠️ 日期范围查询无数据或请求失败:`, result.result)
        return []
      } catch (error) {
        console.error(`❌ 获取日期范围记录失败:`, error)
        return []
      }
    },
    
    // 根据所选时间范围获取日期范围
    getDateRange() {
      const endDate = new Date()
      const startDate = new Date()
      
      switch(this.selectedTimeRange) {
        case '7days':
          startDate.setDate(endDate.getDate() - 6) // 获取最近7天
          break
        case '30days':
          startDate.setDate(endDate.getDate() - 29) // 获取最近30天
          break
        case 'thisMonth':
          // 设置为本月1号
          startDate.setDate(1)
          break
      }
      
      return {
        startDate,
        endDate,
        dayCount: Math.round((endDate - startDate) / (24 * 60 * 60 * 1000)) + 1
      }
    },

    // 准备图表数据
    async prepareChartData() {
      try {
        this.chartLoading = true
        uni.showLoading({
          title: '加载图表数据...'
        })
        console.log('开始准备图表数据...')

        const { startDate, endDate, dayCount } = this.getDateRange()
        const startDateStr = this.formatDateForInput(startDate)
        const endDateStr = this.formatDateForInput(endDate)
        
        console.log(`📅 查询日期范围: ${startDateStr} 至 ${endDateStr}, 共 ${dayCount} 天`)
        
        // 获取日期范围内的所有记录
        const allRecords = await this.fetchRecordsForDateRange(startDateStr, endDateStr)
        
        // 准备日期数组并初始化数据
        const categories = []
        const displayCategories = [] // 用于显示的日期标签（可能简化或省略）
        const milkAmounts = []
        const feedCounts = []
        
        // 创建日期到记录的映射
        const recordsByDate = {}
        
        // 将记录按日期分组
        allRecords.forEach(record => {
          if (!recordsByDate[record.date]) {
            recordsByDate[record.date] = []
          }
          recordsByDate[record.date].push(record)
        })
        
        // 填充每一天的数据
        for (let i = 0; i < dayCount; i++) {
          const currentDate = new Date(startDate)
          currentDate.setDate(startDate.getDate() + i)
          const dateStr = this.formatDateForInput(currentDate)
          const fullDisplayDate = this.formatDateForChart(currentDate)
          
          // 为tooltip保存完整日期
          categories.push(fullDisplayDate)
          
          // 根据时间范围决定x轴显示的日期格式
          let displayDate
          if (dayCount > 15) {
            // 长时间范围使用简化格式显示
            if (i === 0 || currentDate.getDate() === 1 || i === dayCount - 1) {
              // 对于首日、月初和末日使用完整格式
              displayDate = fullDisplayDate
            } else if (i % 5 === 0) {
              // 每隔5天显示一个简化日期
              displayDate = this.formatDateForChartSimple(currentDate)
            } else {
              // 其余日期使用点号表示
              displayDate = '·'
            }
          } else {
            // 短时间范围使用标准格式
            displayDate = fullDisplayDate
          }
          
          displayCategories.push(displayDate)
          
          // 获取当天的记录
          const dayRecords = recordsByDate[dateStr] || []
          
          // 计算当天总奶量和次数
          const totalAmount = dayRecords.reduce(
            (sum, record) => sum + (parseInt(record.amount) || 0),
            0
          )
          const totalCount = dayRecords.length

          console.log(
            `📈 ${dateStr}: 总奶量=${totalAmount}ml, 次数=${totalCount}`
          )

          milkAmounts.push(totalAmount)
          feedCounts.push(totalCount)
        }

        console.log('📋 最终数据汇总:')
        console.log('完整日期:', categories)
        console.log('显示日期:', displayCategories)
        console.log('奶量数组:', milkAmounts)
        console.log('次数数组:', feedCounts)

        // 更新奶量图表数据
        this.milkAmountChartData = {
          categories: categories, // 使用完整日期以便tooltip正确显示
          series: [
            {
              name: '每日总奶量',
              data: milkAmounts,
              color: '#ff69b4'
            }
          ]
        }

        // 更新次数图表数据
        this.feedCountChartData = {
          categories: categories, // 使用完整日期以便tooltip正确显示
          series: [
            {
              name: '每日次数',
              data: feedCounts,
              color: '#ff69b4'
            }
          ]
        }

        console.log('奶量图表数据已准备:', this.milkAmountChartData)
        console.log('次数图表数据已准备:', this.feedCountChartData)
        
        // 调整图表配置以适应数据
        if (dayCount > 15) {
          // 当数据点较多时调整图表配置
          const chartOptions = {
            xAxis: {
              disableGrid: true,
              fontSize: 10, // 减小字体
              fontColor: '#ffffff',
              axisLineColor: '#ffffff',
              itemCount: Math.min(10, dayCount), // 控制x轴显示的标签数量
              boundaryGap: true, // 边界留白
              // 自定义标签显示，替换为简化后的日期
              formatter: (val, index) => {
                return displayCategories[index] || '';
              }
            },
            extra: {
              line: {
                type: 'curve',
                width: 2,
                activeType: 'hollow',
                animation: true
              },
              column: {
                width: 15, // 减小柱宽度
                seriesGap: 1,
                categoryGap: 2
              },
              tooltip: {
                showCategory: true,
                bgColor: '#000000',
                bgOpacity: 0.7,
                fontSize: 10,
                fontColor: '#FFFFFF'
              }
            }
          }
          
          // 更新图表配置
          this.milkAmountChartOpts = {
            ...this.milkAmountChartOpts,
            ...chartOptions
          }
          
          this.feedCountChartOpts = {
            ...this.feedCountChartOpts,
            ...chartOptions
          }
        }
        
        this.chartLoading = false
        uni.hideLoading()
      } catch (error) {
        console.error('准备图表数据失败:', error)
        this.chartLoading = false
        uni.hideLoading()
        uni.showToast({
          title: '数据加载失败',
          icon: 'error'
        })
      }
    },

    // 奶量趋势图表点击事件
    onMilkAmountChartClick(e) {
      console.log('奶量趋势图表点击事件:', e)
      // 不再显示提示
    },

    // 喂养次数图表点击事件
    onFeedCountChartClick(e) {
      console.log('喂养次数图表点击事件:', e)
      // 不再显示提示
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #181828;
  position: relative;
  overflow: hidden;
}

.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at 50% 10%, rgba(80, 40, 100, 0.4) 0%, rgba(24, 24, 40, 0.8) 80%);
  z-index: 0;
}

/* 主内容区 */
.content-wrapper {
  position: relative;
  z-index: 10;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航区 */
.top-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 60rpx 30rpx 20rpx;
  position: relative;
}

.floating-close-btn {
  width: 70rpx;
  height: 70rpx;
  border-radius: 35rpx;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
}

.floating-close-btn:active {
  transform: scale(0.95);
  background: rgba(255, 255, 255, 0.25);
}

.close-icon {
  font-size: 36rpx;
  color: #fff;
  font-weight: 200;
}

.page-title {
  flex: 1;
  text-align: center;
}

.title-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.5);
}

.placeholder {
  width: 70rpx;
}

/* 时间范围选择器 */
.time-range-selector {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 30rpx;
  gap: 20rpx;
}

.time-range-option {
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  font-size: 26rpx;
  text-align: center;
  transition: all 0.3s;
}

.time-range-option.active {
  background: rgba(255, 105, 180, 0.8);
  box-shadow: 0 0 15rpx rgba(255, 105, 180, 0.5);
  transform: scale(1.05);
  font-weight: bold;
}

.time-range-option:active {
  transform: scale(0.95);
}

/* 内容区域 */
.content-section {
  flex: 1;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.chart-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20rpx;
  padding: 30rpx 20rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.2);
}

.summary-item {
  text-align: center;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.summary-label {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 500;
}

.summary-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #ff69b4;
  text-shadow: 0 2rpx 8rpx rgba(255, 105, 180, 0.5);
}

.chart-section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20rpx;
  padding: 25rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.2);
}

.chart-section-title {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.title-icon {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  box-shadow: 0 0 10rpx rgba(255, 255, 255, 0.5);
}

.chart-section-title .title-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: 500;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.chart-wrapper {
  width: 100%;
  padding: 10rpx 0;
  border-radius: 16rpx;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.05);
}
</style> 